<?php

namespace Admin\Controller;

class UserController extends AdminController
{
    public function index()
    {
        // A('Public')->sendMsg();
        $Part = A('Part');
        $partlist = $Part->viewlist();
        $this->assign('partlist', $partlist);
        $Project = A('Project');
        $Projectlist = $Project->viewWidgetIndex();
        $this->assign('projectlist', $Projectlist);
        $this->display();
    }

    public function view()
    {
        //Load('extend');
        $n = D("User");
        import("ORG.Util.Page"); //导入分页类
        $page = $_POST["page"];
        $rows = $_POST["rows"];
        $sort = $_POST["sort"] ? $_POST["sort"] : 'part';
        $order = $_POST["order"] ? $_POST["order"] : 'desc';

        $condition_project_user['project_id'] = session("projectid");
        $useridarray = M('project_user')->where($condition_project_user)->getField('user_id', true);
        $condition['id'] = array('in', $useridarray);

        if ($sort == 'part') {
            $sort = 'partid';
        }
        //dump($order);
        if ($_POST["account"] != null && $_POST["account"] != "") {
            $condition['account'] = array('like', '%' . $_POST["account"] . '%');
        }
        if (I("partid") != null && I("partid") != "") {
            $condition['partid'] = I("partid");
        }
        if ($_POST["createdatetimeStart"] != null && $_POST["createdatetimeStart"] != "") {
            $condition['create_time'] = array('between', $_POST["createdatetimeStart"], $_POST["createdatetimeEnd"]);
        }
        if ($_POST["modifydatetimeStart"] != null && $_POST["modifydatetimeStart"] != "") {
            $condition['update_time'] = array('between', $_POST["modifydatetimeStart"], $_POST["modifydatetimeEnd"]);
        }
        $condition['status'] = "可用";
        $count = $n->where($condition)->count(); //计算总数
        //$p = new Page($count,$rows);order($sort+','+$order)->
        $list = $n->cache(true, 5)->relation(true)->where($condition)->page($page, $rows)->order(array($sort => $order))->select();
        foreach ($list as $key => $value) {
            $list[$key]['partpid'] = $value['part']['pid'];
        }
        //dump($n->getLastSql());
        $list = json_encode($list);
        $result = '{"total":' . $count . ',"rows":' . $list . '}';
        echo($result); //输出json数据
    }

    public function viewlist()
    {
        //Load('extend');
        $n = D("User");
        import("ORG.Util.Page"); //导入分页类
        $page = $_POST["page"];
        $rows = $_POST["rows"];
        $sort = $_POST["sort"] ? $_POST["sort"] : 'part';
        $order = $_POST["order"] ? $_POST["order"] : 'desc';
        if ($sort == 'part') {
            $sort = 'partid';
        }
        //dump($order);
        if ($_POST["account"] != null && $_POST["account"] != "") {
            $condition['account'] = array('like', '%' . $_POST["account"] . '%');
        }
        if (I("partid") != null && I("partid") != "") {
            $condition['partid'] = I("partid");
        }
        if ($_POST["createdatetimeStart"] != null && $_POST["createdatetimeStart"] != "") {
            $condition['create_time'] = array('between', $_POST["createdatetimeStart"], $_POST["createdatetimeEnd"]);
        }
        if ($_POST["modifydatetimeStart"] != null && $_POST["modifydatetimeStart"] != "") {
            $condition['update_time'] = array('between', $_POST["modifydatetimeStart"], $_POST["modifydatetimeEnd"]);
        }
        $condition['status'] = "可用";
        $count = $n->where($condition)->count(); //计算总数
        //$p = new Page($count,$rows);order($sort+','+$order)->
        $list = $n->relation(true)->where($condition)->page($page, $rows)->order(array($sort => $order))->select();
        foreach ($list as $key => $value) {
            $list[$key]['partpid'] = $value['part']['pid'];
        }
        //dump($n->getLastSql());
        $list = json_encode($list);
        $result = '{"total":' . $count . ',"rows":' . $list . '}';
        return ($result); //输出json数据
    }

    //添加用户提交处理
    public function add()
    {
        if (empty($_POST)) {
            $Project = A('Project');
            $projectlist = $Project->viewlist();
            $this->assign('projectlist', $projectlist);
            $Role = A('Role');
            $rolelist = $Role->viewlist();
            $this->assign('rolelist', $rolelist);
            $Part = A('Part');
            $partlist = $Part->viewlist();
            $this->assign('partlist', $partlist);
            $this->display();
        } else {
            $m = D("User");
            $roleId = $_POST['roleIds'];
            $projectids = $_POST['projectid'];
            if (!$vo = $m->create($_POST)) {
                $this->error($m->getError(), 3);
            } else {
                if ($result = $m->add($vo)) {
                    $this->addRole($result, $roleId);
                    $this->addProject($result, $projectids);
                    $this->success('添加用户成功！', 1);
                } else {
                    $this->error('添加用户失败！' . $m->getError(), 0);
                }
            }
        }
    }

    protected function addRole($userId, $roleId)
    {
        //新增用户自动加入相应权限组
        $RoleUser = M("role_user");
        $data['uid'] = $userId;
        $data['group_id'] = $roleId;
        $RoleUser->create($data);
        $RoleUser->add($data);
    }

    protected function addProject($userId, $projectids)
    {
        //用户加入相应项目组
        $temp = M("project_user");
        foreach ($projectids as $key => $v) {
            $data['user_id'] = $userId;
            $data['project_id'] = $v;
            $temp->create($data);
            $temp->add($data);
        }

    }

    // 更新数据
    public function edit()
    {
        if (empty($_POST)) {
            $Project = A('Project');
            $projectlist = $Project->viewlist();
            $this->assign('projectlist', $projectlist);
            $Role = A('Role');
            $rolelist = $Role->viewlist();
            $this->assign('rolelist', $rolelist);
            $Part = A('Part');
            $partlist = $Part->viewlist();
            $this->assign('partlist', $partlist);
            $this->display();
        } else {
            $Form = D("User");
            $userId = $_POST['id'];
            $roleId = $_POST['roleIds'];
            $projectids = $_POST['projectid'];
            if ($vo = $Form->create()) {
                $list = $Form->save($vo);
                $this->editRole($userId, $roleId);
                $this->editProject($userId, $projectids);
                $this->success('更新成功！', 1);
            } else {
                $this->error($Form->getError(), 3);
            }
        }
    }

    protected function editRole($userId, $roleId)
    {
        //编辑用户时编辑相应权限
        $RoleUser = M("role_user");
        //dump($roleId);
        $data['uid'] = $userId;
        $data['group_id'] = $roleId;
        $con['uid'] = $userId;
        $RoleUser->where($con)->delete();
        //$RoleUser->create($data);
        $res = $RoleUser->add($data);
    }

    protected function editProject($userId, $projectids)
    {
        //编辑用户时编辑相应项目组
        $temp = M("project_user");
        $condition['user_id'] = $userId;
        $temp->where($condition)->delete();
        foreach ($projectids as $key => $v) {
            $data['user_id'] = $userId;
            $data['project_id'] = $v;
            $temp->create($data);
            $temp->add($data);
        }
    }

    // 删除数据
    public function delete()
    {
        if (!empty($_GET['ids'])) {
            $d = M("user");
            $condition['id'] = array('in', $_GET['ids']);
            $result = $d->where($condition)->delete();
            if (false !== $result) {
                $RoleUser = M("role_user");
                $condition1['uid'] = array('in', $_GET['ids']);
                $RoleUser->where($condition1)->delete();
                $this->success('删除用户成功！', 1);
            } else {
                $this->error('删除出错！', 1);
            }
        } else {
            $this->error('删除项不存在！', 1);
        }
    }

    // 更新数据
    public function editPwd()
    {
        $Form = D("user");
        $_POST['bind_p'] = ($_POST['password']);
        $_POST['password'] = md5($_POST['password']);
        if ($vo = $Form->create()) {
            $list = $Form->save($_POST);
            if ($list !== false) {
                $this->success('更新成功！', 1);
            } else {
                $this->error('没有更新任何数据!', 0);
            }
        } else {
            $this->error($Form->getError(), 3);
        }
    }

    //用户公共信息组件
    public function viewWidget()
    {
        $n = D("User");
        $list = $n->select();
        $list = json_encode($list);
        echo($list);
    }

    /////////////获取项目客服组件
    public function viewWidgetPatient()
    {
        $n = D("User");
        $projectid = session('projectid');
        $project = M('Project')->find($projectid);
        $con['id'] = array('in', $project['userids']);
        $list = $n->where($con)->select();
        $list = json_encode($list);
        echo($list);
    }

    public function viewWidgetPatientDaoyi()
    {
        $n = D("User");
        $projectid = session('projectid');
        $project_user = M('project_user')->where("project_id=" . $projectid)->getField('user_id', true);
        $con['id'] = array('in', $project_user);
        $con['partname'] = '医助';
        $list = $n->where($con)->select();
        $list = json_encode($list);
        return ($list);
    }

    public function viewWidgetCombogrid()
    {
        $n = D("User");
        import("ORG.Util.Page"); //导入分页类
        $page = empty($_POST["page"]) ? 1 : $_POST["page"];
        $rows = empty($_POST["rows"]) ? 2000 : $_POST["rows"];
        $sort = empty($_POST["sort"]) ? "partid" : $_POST["sort"];
        $order = empty($_POST["order"]) ? "desc" : $_POST["order"];

        $condition_project_user['project_id'] = session("projectid");
        $useridarray = M('project_user')->where($condition_project_user)->getField('user_id', true);
        $condition['id'] = array('in', $useridarray);

        $condition['status'] = "可用";
        $count = $n->where($condition)->count(); //计算总数
        $list = $n->cache(true, 36000)->relation(true)->where($condition)->page($page, $rows)->order(array($sort => $order))->select();
        $list = json_encode($list);
        $result = '{"total":' . $count . ',"rows":' . $list . '}';
        return $list; //输出json数据
    }
}
